package cn.tedu.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.regex.Pattern;

//@Component
public class TokenGlobalFilter implements GlobalFilter, Ordered {
    //定义正则表达式字符串
    private static final String TOKEN_REGEX = "\\d{10}";
    //将正则表达式字符串编译成Pattern对象，Pattern 对象是编译后的正则表达式的表示形式，它可以被重复使用来进行高效的字符串匹配操作
    private static final Pattern TOKEN_PATTERN = Pattern.compile(TOKEN_REGEX);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //从请求参数中获取token
        String token = request.getQueryParams().getFirst("token");
        //校验token是否满足要求
        if (isValidToken(token)) {
            //认证通过，放行请求
            return chain.filter(exchange);
        } else {
            //认证失败，返回错误信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
    }

    private boolean isValidToken(String token) {
        //保证token不为null，且token对应的值不为空，并且长度满足正则表达式
        return token != null && !token.isEmpty() && TOKEN_PATTERN.matcher(token).matches();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}